package cn.hfatec.shms.web.yk.ykJkgl.service;

import java.io.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


import cn.hfatec.JsonResponse;
import cn.hfatec.constants.SysContant;
import cn.hfatec.shms.advice.annotation.MysqlDataSource;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.constants.ShmsProperties;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.enums.KeyTypeEnum;
import cn.hfatec.shms.exception.KeyGenException;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.system.organization.model.Organization;
import cn.hfatec.shms.system.organization.service.OrganizationService;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.utils.ExcelUtil;
import cn.hfatec.shms.utils.KeyGenUtils;
import cn.hfatec.shms.web.members.customer.model.Customer;
import cn.hfatec.shms.web.td.tdHzb.model.TdHzb;
import cn.hfatec.shms.web.td.tdHzb.model.TdHzbParams;
import cn.hfatec.shms.web.td.tdMxb.model.TdCheck;
import cn.hfatec.shms.web.td.tdMxb.model.TdMxb;
import cn.hfatec.shms.web.yk.ykGather.model.YkGather;
import cn.hfatec.shms.web.yk.ykGather.service.YkGatherService;
import cn.hfatec.shms.web.yk.ykJkgl.model.JkglCheck;
import cn.hfatec.shms.web.yk.ykTj.model.YkTj;
import com.google.common.base.Optional;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hfatec.base.BaseDao;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.shms.web.yk.ykJkgl.model.YkJkgl;
import cn.hfatec.shms.web.yk.ykJkgl.dao.YkJkglDao;
import cn.hfatec.shms.web.yk.ykJkgl.model.YkJkglParams;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author hfatec
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Service("YkJkglService")
public class YkJkglService {

    public static final String BEAN_ID = "YkJkglService";

    //注入Dao层
    @Resource(name = "YkJkglDao")
    private YkJkglDao ykJkglDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;

    @Resource(name = "shmsProperties")
    private ShmsProperties shmsProperties;

    //服务层
    @Resource(name = "OrganizationService")
    private OrganizationService organizationService;
    //服务层
    @Resource(name = "YkGatherService")
    private YkGatherService ykGatherService;

    @Transactional
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询数据
     *
     * @param ykJkglParams
     * @param page
     */
    @Transactional
    public Table queryYkJkglTable(YkJkglParams ykJkglParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", ykJkglParams);
        return baseDao.queryTableByPage("queryYkJkgl", params, page);
    }

    /**
     * 查询数据
     *
     * @param ykJkglParams
     *
     */
    @Transactional
    public YkJkgl hjYkJkgl(YkJkglParams ykJkglParams) {
        return ykJkglDao.hjYkJkgl(ykJkglParams);
    }

    /**
     * 插入数据
     *
     * @param ykJkgl
     */
    @Transactional
    public String saveYkJkgl(YkJkgl ykJkgl, User user) throws KeyGenException {
        if (ykJkgl.getId() != null) {
            YkJkgl result = getYkJkgl(ykJkgl.getId());
            if (result != null) {
                ykGatherService.deleteYkGather(result.getJkglId());
                String[] payments = null;
                if (ykJkgl.getPayment() != null) {
                    String payment = ykJkgl.getPayment().replace("，", ",") + ",";
                    if (StringUtils.isNotBlank(payment)) {
                        if (payment.contains(",")) {
                            payments = payment.split(",");
                        }
                    }
                }
                String[] sprices = null;
                if (ykJkgl.getSprice() != null) {
                    String sprice = ykJkgl.getSprice().replace("，", ",") + ",";
                    if (StringUtils.isNotBlank(sprice)) {
                        if (sprice.contains(",")) {
                            sprices = sprice.split(",");
                        }
                    }
                }
                if (payments.length != sprices.length) {
                    return new JsonResponse(JsonResponse.RETURN_FAILURE, "收款方式和收款金额个数不等").toString();

                }
                YkGather ykGather = new YkGather();
                for (int i = 0; i < payments.length; i++) {
                    ykGather.setBillId(result.getJkglId());
                    ykGather.setGatherType(payments[i]);
                    ykGather.setGatherMoney(sprices[i]);
                    ykGatherService.saveYkGather(ykGather);
                }

                ykJkglDao.update(ykJkgl);
            } else {
                ykJkgl.setJkglId(KeyGenUtils.createKeyByType(KeyTypeEnum.JKGL_KEY));
                String[] payments = null;
                if (ykJkgl.getPayment() != null) {
                    String payment = ykJkgl.getPayment().replace("，", ",") + ",";
                    if (StringUtils.isNotBlank(payment)) {
                        if (payment.contains(",")) {
                            payments = payment.split(",");
                        }
                    }
                }
                String[] sprices = null;
                if (ykJkgl.getSprice() != null) {
                    String sprice = ykJkgl.getSprice().replace("，", ",") + ",";
                    if (StringUtils.isNotBlank(sprice)) {
                        if (sprice.contains(",")) {
                            sprices = sprice.split(",");
                        }
                    }
                }
                if (payments.length != sprices.length) {
                    return new JsonResponse(JsonResponse.RETURN_FAILURE, "收款方式和收款金额个数不等").toString();

                }
                YkGather ykGather = new YkGather();
                for (int i = 0; i < payments.length; i++) {
                    ykGather.setBillId(ykJkgl.getJkglId());
                    ykGather.setGatherType(payments[i]);
                    ykGather.setGatherMoney(sprices[i]);
                    ykGatherService.saveYkGather(ykGather);
                }
                ykJkgl.setCreateTime(new Date());
                ykJkgl.setCreateName(user.getLoginName());
                ykJkglDao.insert(ykJkgl);
            }
        } else {
            ykJkgl.setJkglId(KeyGenUtils.createKeyByType(KeyTypeEnum.JKGL_KEY));
            String[] payments = null;

            if (ykJkgl.getPayment() != null) {
                String payment = ykJkgl.getPayment().replace("，", ",") + ",";
                if (StringUtils.isNotBlank(payment)) {
                    if (payment.contains(",")) {
                        payments = payment.split(",");
                    }
                }
            }
            String[] sprices = null;
            if (ykJkgl.getSprice() != null) {
                String sprice = ykJkgl.getSprice().replace("，", ",") + ",";
                if (StringUtils.isNotBlank(sprice)) {
                    if (sprice.contains(",")) {
                        sprices = sprice.split(",");
                    }
                }
            }
            if (payments.length != sprices.length) {
                return new JsonResponse(JsonResponse.RETURN_FAILURE, "收款方式和收款金额个数不等").toString();

            }
            YkGather ykGather = new YkGather();
            for (int i = 0; i < payments.length; i++) {
                ykGather.setBillId(ykJkgl.getJkglId());
                ykGather.setGatherType(payments[i]);
                ykGather.setGatherMoney(sprices[i]);
                ykGatherService.saveYkGather(ykGather);
            }
            ykJkgl.setCreateTime(new Date());
            ykJkgl.setCreateName(user.getLoginName());
            ykJkglDao.insert(ykJkgl);
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 删除数据
     *
     * @param id
     */
    @Transactional
    public void deleteYkJkgl(Integer id) {
        YkJkgl ykJkgl=getYkJkgl(id);
        if(ykJkgl!=null)
        {
            ykGatherService.deleteYkGather(ykJkgl.getJkglId());
        }
        ykJkglDao.delete(id);
    }

    /**
     * 删除数据
     *
     * @param ykJkglList
     */
    @Transactional
    public void deleteYkJkglBatch(List<String> ykJkglList) {
        for (String id : ykJkglList) {
            deleteYkJkgl(Integer.valueOf(id));
        }
    }

    /**
     * 根据ID获取数据
     *
     * @param id
     */
    @Transactional
    public YkJkgl getYkJkgl(Integer id) {

        return ykJkglDao.getYkJkglById(id);
    }

    /**
     * 根据ID获取数据
     *
     * @param productName
     */
    @Transactional
    public YkJkgl getCost(String productName) {
    return ykJkglDao.getYkCost(productName);
    }

    /**
     * 导入健康管理数据
     *
     * @param path
     * @param request
     * @param response
     * @return
     * @throws java.io.IOException
     */
    @Transactional
    @MysqlDataSource
    public String importCust(String path, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filePath = path.substring(path.indexOf("/upload") + 7);
        User user = (User) request.getSession().getAttribute(ShmsConstant.LOGIN_USER_SESSION_NAME);
        Organization organization = new Organization();
        if (user == null) {
            throw new NotAuthException("用户未授权");
        } else {
            organization = organizationService.getOrganizationByOrgId(user.getOrgId());
        }
        String uploadPath = shmsProperties.getUploadPath();
        File file = new File(uploadPath + File.separator + filePath);
        boolean flag = false;
        String rule = "^1[358]\\d{9}$";
        String errorMsg = "";
        Workbook workbook = null;
        workbook = WorkbookFactory.create(file);
        Sheet sh = workbook.getSheetAt(0);//
        List<JkglCheck> potentialCusts = this.buildCustWithAjaxUpload(sh);//
        if (potentialCusts != null && potentialCusts.size() > 0) {
            for (JkglCheck jkglCheck : potentialCusts) {
                //判读是否为有效数据
                if (jkglCheck.isValid()) {
                    YkJkgl ykJkgl = jkglCheck.getYkJkgl();
                    if (organization != null) {
                        ykJkgl.setOrgLevelCode(organization.getOrgLevelCode());
                    }
                    Optional<JsonResponse<String>> optional = checkCustByUniqueConstraint(ykJkgl);
                    if (optional.isPresent()) {
                        errorMsg += "第" + jkglCheck.getRowNumber() + "收款方式和收款金额个数不等,不能导入!";
                        continue;
                    }
                    YkJkgl ykCost =getCost(ykJkgl.getProductName());
                    if (ykCost != null) {
                        ykJkgl.setCost(ykCost.getCost());
                    }
                    saveYkJkgl(ykJkgl, user);
                    flag = true;
                } else {//无效数据
                    errorMsg += "第" + jkglCheck.getRowNumber() + "有错，不能导入!";
                }
            }
        } else {
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "导入的文件无符合数据").toString();
        }

        if (flag) {
            if ("".equals(errorMsg)) {
                return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "导入成功!" + errorMsg).toString();
            }
            return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "部分导入成功!" + errorMsg).toString();
        } else {
            return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "导入失败!" + errorMsg).toString();
        }

    }

    public Date luDate(String strDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public String stringDate(Date billTime) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String sDate=sdf.format(billTime);
       return sDate;
    }

    /**
     * 读取潜在客户导入的数据
     *
     * @param sh
     * @return
     * @throws Exception
     */
    @Transactional
    @MysqlDataSource
    private List<JkglCheck> buildCustWithAjaxUpload(Sheet sh) throws Exception {
        List<JkglCheck> checks = new ArrayList<JkglCheck>();
        int rows = sh.getLastRowNum() + 1 - sh.getFirstRowNum(); // 总行数
        List<CodeInfo> sexList = CodeInfoCache.getCodeInfo(CodeType.SEX);
        List<CodeInfo> vipList = CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE);
        List<CodeInfo> jkglList = CodeInfoCache.getCodeInfo(CodeType.JKGL_TYPE);
        List<CodeInfo> channelList = CodeInfoCache.getCodeInfo(CodeType.JKGLQD_TYPE);
        List<CodeInfo> AKList = CodeInfoCache.getCodeInfo(CodeType.AK_TYPE);
        ExcelUtil excelUtil = new ExcelUtil();
        for (int i = 1; i < rows; i++) {
            boolean flag = true;//数据是否有效(客户姓名，手机号存在)
            boolean flag2 = false;//判断是否该行有数据
            YkJkgl ykJkgl = new YkJkgl();
            JkglCheck jkglCheck = new JkglCheck();
            jkglCheck.setRowNumber(i + 1);
            jkglCheck.setValid(true);
            String str = "";//下拉框
            // HSSFRow row = sh.getRow(i);//excel97-2003写法
            Row row = sh.getRow(i);
//            int cols = row.getLastCellNum() + 1 - row.getFirstCellNum(); // 该行的总列数
            Iterator cells = row.cellIterator();
            int j = 0;
            while (cells.hasNext()) {

//                HSSFCell cell = (HSSFCell) cells.next();//excel97-2003写法
                XSSFCell cell = (XSSFCell) cells.next();

                if (j == 0) {
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykJkgl.setBookId(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 1) {
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykJkgl.setCardId(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 2) {

                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykJkgl.setUserName(ExcelUtil.getStringRowCellValue(row, j));
                    }

                } else if (j == 3) {
                    // 年龄
                    str = excelUtil.getStringRowCellValue(row, j);
                    if (!StringUtils.isEmpty(str)) {
                        for (CodeInfo c : sexList) {
                            if (c.getContent().equals(str)) {
                                ykJkgl.setSex(c.getValue());
                            }
                        }
                    }

                } else if (j == 4) {
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykJkgl.setAge(ExcelUtil.getStringRowCellValue(row, j));
                    }// 性别
                } else if (j == 5) {
                    // 电话
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykJkgl.setPhone(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 6) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykJkgl.setIdentity(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 7) {
                    // 地址
                    str = excelUtil.getStringRowCellValue(row, j);
                    if (!StringUtils.isEmpty(str)) {
                        for (CodeInfo c : vipList) {
                            if (c.getContent().equals(str)) {
                                ykJkgl.setJkglType(c.getValue());
                            }
                        }
                    }


                } else if (j == 8) {
                    // 身份证

                    str = excelUtil.getStringRowCellValue(row, j);
                    if (!StringUtils.isEmpty(str)) {
                        for (CodeInfo c : AKList) {
                            if (c.getContent().equals(str)) {
                                ykJkgl.setSpareA(c.getValue());
                            }
                        }
                    }

                } else if (j == 9) {
                    // 身份证

                    if (!StringUtils.isEmpty(excelUtil.getRowCellValueDate(row, j).toString())) {
                     ykJkgl.setBillTime(stringDate(excelUtil.getRowCellValueDate(row, j)));
                    }
                } else if (j == 10) {
                    // 身份证
                    str = excelUtil.getStringRowCellValue(row, j);
                    if (!StringUtils.isEmpty(str)) {
                        for (CodeInfo c : jkglList) {
                            if (c.getContent().equals(str)) {
                                ykJkgl.setProductName(c.getValue());
                            }
                        }
                    }

                } else if (j == 11) {

                    str = excelUtil.getStringRowCellValue(row, j);
                    if (!StringUtils.isEmpty(str)) {
                        for (CodeInfo c : channelList) {
                            if (c.getContent().equals(str)) {
                                ykJkgl.setChannelType(c.getValue());
                            }
                        }
                    }
                } else if (j == 12) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykJkgl.setMoney(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 13) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykJkgl.setJkglFg(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 14) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykJkgl.setPayment(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 15) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        ykJkgl.setSprice(excelUtil.getStringRowCellValue(row, j));
                    }
                }

                j++;
            }
            if (flag) {
//                 list.add(cust);
                jkglCheck.setYkJkgl(ykJkgl);
                checks.add(jkglCheck);
            } else {
//                TdCheck.setCustom(cust);
                if (flag2) {
                    checks.add(jkglCheck);
                }
            }
        }
        return checks;
    }

    /**
     * 根据客户姓名和手机查询唯一性
     *
     * @param ykJkgl
     * @return
     */
    @Transactional
    public Optional checkCustByUniqueConstraint(YkJkgl ykJkgl) {
        String payment = ykJkgl.getPayment().replace("，", ",");
        String sprice = ykJkgl.getSprice().replace("，", ",");
        int l = lenghtNum(payment);
        int s = lenghtNum(sprice);
        if (l != s) {
            return Optional.of(new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "收款方式和收款金额个数不等!"));
        }
        return Optional.absent();
    }

    public int lenghtNum(String lenghts) {
        int a = lenghts.length();
        String b = lenghts.replace(",", "");
        int c = b.length();
        return a - c;
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    public String exportExcel(YkJkglParams ykJkglParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            List dataList = ykJkglDao.queryYkJkgl(ykJkglParams);
            List nameList = new ArrayList();
            nameList.add("健康管理编号");
            nameList.add("预约号");
            nameList.add("卡号");
            nameList.add("客户姓名");
            nameList.add("性别");
            nameList.add("年龄");
            nameList.add("类型");
            nameList.add("AK类型");
            nameList.add("下单日期");
            nameList.add("产品名称");
            nameList.add("渠道类型");
            nameList.add("金额");
            nameList.add("分管人员");
            nameList.add("收款方式");
            nameList.add("收款金额");
            nameList.add("成本");
            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> sexList = CodeInfoCache.getCodeInfo(CodeType.SEX);
        List<CodeInfo> vipList = CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE);
        List<CodeInfo> jkglList = CodeInfoCache.getCodeInfo(CodeType.JKGL_TYPE);
        List<CodeInfo> channelList = CodeInfoCache.getCodeInfo(CodeType.JKGLQD_TYPE);
        List<CodeInfo> AKList = CodeInfoCache.getCodeInfo(CodeType.AK_TYPE);
        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("健康管理表");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        YkJkgl ykJkgl = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            ykJkgl = (YkJkgl) fieldData.get(i);
            // 第四步，创建单元格，并设置值

            if (ykJkgl.getJkglId() == null) {
                row.createCell((short) 0).setCellValue("");
            } else {
                row.createCell((short) 0).setCellValue(ykJkgl.getJkglId());
            }
            if (ykJkgl.getBookId() == null) {
                row.createCell((short) 1).setCellValue("");
            } else {
                row.createCell((short) 1).setCellValue(ykJkgl.getBookId());
            }
            if (ykJkgl.getCardId() == null) {
                row.createCell((short) 2).setCellValue("");
            } else {
                row.createCell((short) 2).setCellValue(ykJkgl.getCardId());
            }
            if (ykJkgl.getUserName() == null) {
                row.createCell((short) 3).setCellValue("");
            } else {
                row.createCell((short) 3).setCellValue(ykJkgl.getUserName());
            }
            if (ykJkgl.getSex() == null) {
                row.createCell((short) 4).setCellValue("");
            } else {
                for (CodeInfo c : sexList) {//汉化性别信息
                    if (c.getValue().equals(ykJkgl.getSex() + "")) {
                        row.createCell((short) 4).setCellValue(c.getContent());
                        break;
                    }
                }
            }
            if (ykJkgl.getAge() == null) {
                row.createCell((short) 5).setCellValue("");
            } else {
                row.createCell((short) 5).setCellValue(ykJkgl.getAge());
            }
            if (ykJkgl.getJkglType() == null) {
                row.createCell((short) 6).setCellValue("");
            } else {

                for (CodeInfo c : vipList) {//汉化性别信息
                    if (c.getValue().equals(ykJkgl.getJkglType() + "")) {
                        row.createCell((short) 6).setCellValue(c.getContent());
                        break;
                    }
                }

            }
            if (ykJkgl.getSpareA() == null) {
                row.createCell((short) 7).setCellValue("");
            } else {
                for (CodeInfo c : AKList) {//汉化性别信息
                    if (c.getValue().equals(ykJkgl.getSpareA() + "")) {
                        row.createCell((short) 7).setCellValue(c.getContent());
                        break;
                    }
                }

            }
            if (ykJkgl.getBillTime() == null) {
                row.createCell((short) 8).setCellValue("");
            } else {
                row.createCell((short) 8).setCellValue(ykJkgl.getBillTime());
            }
            if (ykJkgl.getProductName() == null) {
                row.createCell((short) 9).setCellValue("");
            } else {

                for (CodeInfo c : jkglList) {//汉化性别信息
                    if (c.getValue().equals(ykJkgl.getProductName() + "")) {
                        row.createCell((short) 9).setCellValue(c.getContent());
                        break;
                    }
                }

            }
            if (ykJkgl.getChannelType() == null) {
                row.createCell((short) 10).setCellValue("");
            } else {
                for (CodeInfo c : channelList) {//汉化性别信息
                    if (c.getValue().equals(ykJkgl.getChannelType() + "")) {
                        row.createCell((short) 10).setCellValue(c.getContent());
                        break;
                    }
                }

            }
            if (ykJkgl.getMoney() == null) {
                row.createCell((short) 11).setCellValue("");
            } else {
                row.createCell((short) 11).setCellValue(ykJkgl.getMoney());
            }
            if (ykJkgl.getJkglFg() == null) {
                row.createCell((short) 12).setCellValue("");
            } else {
                row.createCell((short) 12).setCellValue(ykJkgl.getJkglFg());
            }
            if (ykJkgl.getPayment() == null) {
                row.createCell((short) 13).setCellValue("");
            } else {
                row.createCell((short) 13).setCellValue(ykJkgl.getPayment());
            }
            if (ykJkgl.getSprice() == null) {
                row.createCell((short) 14).setCellValue("");
            } else {
                row.createCell((short) 14).setCellValue(ykJkgl.getSprice());
            }
            if (ykJkgl.getCost() == null) {
                row.createCell((short) 15).setCellValue("");
            } else {
                row.createCell((short) 15).setCellValue(ykJkgl.getCost());
            }




        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }


        return wb;
    }


    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }
}